package service

import (
	"context"
	"k8s-dash/utils"
	coreV1 "k8s.io/api/core/v1"
	metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

type node struct{}

var Node node

type NodeResp struct {
	Total int           `json:"total"`
	Items []coreV1.Node `json:"items"`
}

// GetNodeList 获取node节点列表
func (n *node) GetNodeList(filterName string, limit, page int) (nodeRsp *NodeResp, err error) {
	nodeList, err := utils.K8sClient.K8sClient.CoreV1().Nodes().List(context.TODO(), metaV1.ListOptions{})
	if err != nil {
		return nil, err
	}
	//清洗数据
	dataSelect := &dataSelector{
		GenericDataList: n.toCells(nodeList.Items),
		DataSelectQuery: &DataSelectorQuery{
			Filter: &FilterQuery{filterName},
			Paginate: &PageQuery{
				Limit: limit,
				Page:  page,
			},
		},
	}
	filtered := dataSelect.Filter()
	total := len(filtered.GenericDataList)
	data := filtered.Sort().Paginate()
	ns := n.FromCells(data.GenericDataList)
	return &NodeResp{
		Total: total,
		Items: ns,
	}, nil
}

// GetNodeDetail 获取节点的详情
func (n *node) GetNodeDetail(name string) (*coreV1.Node, error) {
	node, err := utils.K8sClient.K8sClient.CoreV1().Nodes().Get(context.TODO(), name, metaV1.GetOptions{})
	if err != nil {
		return nil, err
	}
	return node, nil
}

// 类型转换的方法 coreV1.pod => DataCell,DataCell => coreV1.pod
func (p *node) toCells(nodes []coreV1.Node) []DataCell {
	cells := make([]DataCell, len(nodes))
	for i := range nodes {
		cells[i] = nodeCell(nodes[i])
	}
	return cells
}

func (p *node) FromCells(cells []DataCell) []coreV1.Node {
	nodes := make([]coreV1.Node, len(cells))
	for i := range cells {
		nodes[i] = coreV1.Node(cells[i].(nodeCell))
	}
	return nodes
}
